import { useState } from 'react';
import { Button, Tooltip } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import QrCodeCanvas from '@/components/QrCodeCanvas';
import styles from './index.less';
import { QrcodeInfo } from '@/utils/QrCode/typing';
import { useQRCodeModalDow } from '@/store/adapter/useGlobalStatus';

const Preview = ({ state }: { state: QrcodeInfo }) => {
  const [tooltipVisible, _tooltipVisible] = useState(false);
  const { closeQrcodeMobalDow } = useQRCodeModalDow()


  const DowloadQrcode = () => {
    const canvas = document.querySelector('#ID_qrcode_canvas') as HTMLCanvasElement
    canvas.toBlob(async (blob) => {
      try {
        const a = document.createElement("a");
        a.style.display = "none";
        a.download = '二维码';
        a.href = window.URL.createObjectURL(blob!);
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } catch (error) {
        console.error(error);
      }
    });



  }
  return (
    <div className={styles.Preview}>
      <div className={styles.closeModal} onClick={() => closeQrcodeMobalDow()}>
        <CloseOutlined style={{ color: '#8c8c8c' }} />
      </div>
      <QrCodeCanvas className={styles.canvas} options={state} />
      <div className={styles.tooltip}>建议在真实场景中扫描确认</div>
      <Tooltip
        title="请输入二维码内容"
        onOpenChange={vis => {
          if (vis && !state.text) {
            _tooltipVisible(true);
          } else {
            _tooltipVisible(false);
          }
        }}
        open={tooltipVisible}
      >
        <Button
          onClick={() => DowloadQrcode()}
          style={{ width: '100%' }}
          disabled={!state.text}
          type="primary"
          size="large"
          className={styles.button}
        >
          下载
        </Button>
      </Tooltip>
    </div>
  );
};

export default Preview;
